import {Component, ViewChild, ViewEncapsulation} from '@angular/core';
import {ICellRendererAngularComp} from '@ag-grid-community/angular';
import {ApesCheckboxGroupComponent} from '@shared/apes/checkbox';
import {deepClone} from "../../../utils/utils";

@Component({
  selector: 'apes-cell-opt',
  template: `
    <apes-checkbox-group class="cell-opt" #checkOpt [apesDisabled]="disabled" [(ngModel)]="inputValue"
                         (ngModelChange)="onChange($event)"></apes-checkbox-group>
  `,
  encapsulation: ViewEncapsulation.None,
  styles: [`.cell-opt .apes-checkbox {
    top: -2px !important;
    font-size: 12px !important;
  }

  .cell-opt label {
    font-size: 12px !important;
    color: #000 !important;
  }`]
})
export class EditorOptListComponent implements ICellRendererAngularComp {
  inputValue: any;
  params: any;
  ctx: any;
  disabled = false;

  @ViewChild('checkOpt', {read: ApesCheckboxGroupComponent, static: false}) checkOpt: ApesCheckboxGroupComponent;

  constructor() {
  }

  agInit(params: any): void {
    if (params.hasOwnProperty("colDef")) {
      this.disabled = params.colDef.disabled == true ? true : false;
    } else {
      this.disabled = params.column.colDef.disabled == true ? true : false;
    }

    this.params = params;
    this.inputValue = params.value;
  }


  onChange(param) {
    this.params.value = param;
    let data = deepClone(param);
    this.params.node.setSelected(true);
    for (let inputValueKey in this.inputValue) {
      if (this.inputValue[inputValueKey].checked === false) {
        this.params.node.setSelected(false);
        setTimeout(() =>
          this.params.node.data.operations.forEach(item => {
            data.forEach(data => {
              if (data["operationId"] == item["operationId"])
                item.checked = data.checked;

            })
          })
            , 100);
        return;
      }
    }

  }

  refresh(params: any): boolean {
    params.data[this.params.colDef] = params.value
    params.api.refreshCells(params);
    return false;
  }

}
